package com.sanhe.a448.utils;

import static com.menu.app.util.FunctionCode.START1;
import static com.menu.app.util.FunctionCode.START2;

import com.menu.app.it.RentListener;
import com.menu.app.model.Models;
import com.menu.app.util.pipe.BasePortEventPipe;
import com.menu.app.util.port.SerialManage;
import com.plata.base.aclr.utils.SPHelper;
import com.sanhe.a448.App;

public class PortPipe extends BasePortEventPipe {

    static PortPipe instance;

    public static PortPipe getInstance() {
        if (instance == null) {
            instance = new PortPipe();
        }
        return instance;
    }

    private PortPipe() {
        super();
    }

    @Override
    public void doInit() {
        super.doInit();
        isStart = false;
    }

    @Override
    public boolean setRent(boolean on, final long value, RentListener listener) {
        boolean bo = super.setRent(on, value, listener);
        if (!bo) {
            return false;
        }
        if (on) {
            SPHelper.getInstance(App.getApp()).putBoolean("rent", true).commit();
            Models.Companion.get().getRentEvent().postValue(1);
        } else {
            SPHelper.getInstance(App.getApp()).putBoolean("rent", false).commit();
            Models.Companion.get().getRentEvent().postValue(0);
        }
        for (RentListener l : rentListener) {
            l.onSetRent(true);
        }
        return true;
    }

    @Override
    protected void sendTouchEvent(byte data_H, byte data_L) {
        byte[] touch_event = new byte[9];
        touch_event[0] = START1;
        touch_event[1] = START2;
        touch_event[2] = 6;
        touch_event[3] = (byte) 0x83;
        touch_event[4] = 0x10;
        touch_event[5] = 0xb;
        touch_event[6] = 1;
        touch_event[7] = data_H;
        touch_event[8] = data_L;
        SerialManage.getInstance().send(touch_event);
    }

    GoBack goBack = new GoBack();

    class GoBack implements Runnable {
        Runnable runnable;

        GoBack setRunnable(Runnable run) {
            runnable = run;
            return this;
        }

        @Override
        public void run() {
            if (Const.currentPage > 1) {
                Const.sendTouchEvent(0x83, 0x1e, 1, 1, 0xa);
                h.postDelayed(this, 200);
            } else if (runnable != null) {
                runnable.run();
                runnable = null;
            }
        }
    }

    public void goBack(Runnable runnable) {
        h.removeCallbacks(goBack);
        h.post(goBack.setRunnable(runnable));
    }
}
